<template>
  <div id="app">
    <Header/>
    <hr>
    <List :todos="todos"/>
    <hr>
    <Footer :total="todos.length"/>
  </div>
</template>

<script>
import Header from './components/header';
import List from './components/list';
import Footer from './components/footer';

export default {
  name: 'App',
  components: {
    Header,
    List,
    Footer,
  },
  mounted() {
    this.reload();
    this.$bus.$on('showAll', this.showAll);
    this.$bus.$on('showDone', this.showDone);
    this.$bus.$on('showUndone', this.showUndone);
    this.$bus.$on('changeDone', this.changeDone);
    this.$bus.$on('addTodo', this.addTodo);
    this.$bus.$on('delTodo', this.delTodo);
    this.$bus.$on('clearAll', this.clearAll);
  },
  data() {
    return {
      todos: [],
      backup: [],
      done: [],
      unDone: [],
    };
  },
  // watch: {
  //   todos: {
  //     immediate: true,
  //     handler(val) {
  //       this.backup = this.todos;
  //       this.todos.map((item) => {
  //         item.checked ? this.done.push(item) : this.unDone.push(item);
  //       });
  //       localStorage.setItem('todos', JSON.stringify(val));
  //     },
  //   },
  // },
  computed: {
    getDone() {
      return this.todos.filter(el => el.checked);
    },
    getUndone() {
      return this.todos.filter(el => !el.checked);
    },
  },
  updated() {
    localStorage.setItem('todos', JSON.stringify(this.todos));
  },
  methods: {
    reload() {
      this.todos = [...JSON.parse(localStorage.getItem('todos'))];
    },
    showAll() {
      this.reload();
    },
    showDone() {
      // this.todos = this.getDone;
    },
    showUndone() {
      // this.todos = this.getUndone;
    },
    changeDone(id) {
      this.todos = this.todos.reduce((pre, item) => {
        if (item.id === id) {
          item.checked = !item.checked;
        }
        pre.push(item);
        return pre;
      }, []);
    },
    addTodo(todo) {
      this.todos.unshift(todo);
    },
    delTodo(id) {
      this.todos = this.todos.filter((item) => item.id !== id);
    },
    clearAll() {
      this.todos = [];
    },
  },
};
</script>

<style scoped>
#app {
  display: flex;
  flex-direction: column;
}
</style>
